import React, { useState, useEffect } from 'react';
import { 
  Modal, 
  Form, 
  Card, 
  Button, 
  Input, 
  DatePicker, 
  Table, 
  Avatar,
  Space,
  Typography,
  Upload, 
  message,
} from 'antd';
import { 
  FilterOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ArrowLeftOutlined,
  LoadingOutlined ,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import styles from '../component/Teacher.module.css';
import { ActionPermissionGuard } from './PermissionGuard';

const { RangePicker } = DatePicker;
const { Text } = Typography;
const { TextArea } = Input;
const {Search}=Input

export default function Teacher() {
  const [loading, setLoading] = useState(false);
  const [teachers, setTeachers] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [searchParams, setSearchParams] = useState({});
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [avatarUrl, setAvatarUrl] = useState('');
  const [uploading, setUploading] = useState(false);
  const [formValues, setFormValues] = useState({
    name: '',
    briefIntro: '',
    detailedIntro: '',
    avatar: '',
    phone: ''
  });

  // 获取教师列表
  const fetchTeachers = async (params = {}) => {
    try {
      setLoading(true);
      
      // 检查用户是否已登录
      const currentUser = localStorage.getItem('currentUser');
      if (!currentUser) {
        console.error('用户未登录');
        return;
      }
      
      const queryParams = {
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...params
      };
      
      const token = localStorage.getItem('token');
      const response = await fetch(`http://localhost:3001/api/teachers?${new URLSearchParams(queryParams)}`, {
        headers: {
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
        }
      });
      
      if (!response.ok) {
        if (response.status === 401) {
          console.error('获取教师列表失败: 认证失败');
          message.error('认证失败，请重新登录');
          return;
        }
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      
      if (result.success) {
        setTeachers(result.data);
        setPagination({
          ...pagination,
          total: result.pagination.total
        });
      } else {
        message.error('获取教师列表失败');
      }
    } catch (error) {
      message.error('获取教师列表失败');
      console.error('获取教师列表错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 初始加载数据
  useEffect(() => {
    fetchTeachers();
  }, [pagination.current, pagination.pageSize]);

  // 处理筛选
  const handleFilter = () => {
    const params = {};
    if (searchParams.name) params.name = searchParams.name;
    if (searchParams.dateRange && searchParams.dateRange.length === 2) {
      params.startDate = searchParams.dateRange[0].format('YYYY-MM-DD');
      params.endDate = searchParams.dateRange[1].format('YYYY-MM-DD');
    }
    fetchTeachers(params);
  };

  // 上传头像
  const handleAvatarUpload = async (file) => {
    const formData = new FormData();
    formData.append('avatar', file);
    
    try {
      setUploading(true);
      console.log('开始上传文件:', file.name, file.size, file.type);
      
      const token = localStorage.getItem('token');
      const response = await fetch('http://localhost:3001/api/upload', {
        method: 'POST',
        headers: {
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
        },
        body: formData
      });
      
      console.log('上传响应状态:', response.status);
      
      if (!response.ok) {
        throw new Error(`上传失败: ${response.status}`);
      }
      
      const result = await response.json();
      console.log('上传响应:', result);
      
      if (result.success) {
        const avatarUrl = result.data.url;
        console.log('设置头像URL:', avatarUrl);
        setAvatarUrl(avatarUrl);
        setFormValues({
          ...formValues,
          avatar: avatarUrl
        });
        return avatarUrl;
      } else {
        throw new Error(result.message || '上传失败');
      }
    } catch (error) {
      console.error('头像上传错误:', error);
      message.error('头像上传失败: ' + error.message);
      throw error;
    } finally {
      setUploading(false);
    }
  };

  // 处理表单字段变化
  const handleFormChange = (changedValues, allValues) => {
    setFormValues(allValues);
  };
  // 添加教师
  const handleAddTeacher = async () => {
    try {
      const currentUser = JSON.parse(localStorage.getItem('currentUser'));
      
      if (!currentUser || !currentUser.username) {
        message.error('无法获取当前用户信息');
        return;
      }

      console.log('准备提交的表单数据:', formValues);

      // 创建FormData对象
      const formData = new FormData();
      formData.append('name', formValues.name);
      formData.append('briefIntro', formValues.briefIntro);
      formData.append('detailedIntro', formValues.detailedIntro);
      formData.append('phone', formValues.phone || '');
      formData.append('uploader', currentUser.username);
      
      // 如果有头像URL，直接添加到FormData
      if (formValues.avatar && typeof formValues.avatar === 'string') {
        formData.append('avatar', formValues.avatar);
        console.log('添加头像URL到FormData:', formValues.avatar);
      }

      console.log('发送请求到:', 'http://localhost:3001/api/addteachers');

      const token = localStorage.getItem('token');
      const response = await fetch('http://localhost:3001/api/addteachers', {
        method: 'POST',
        headers: {
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
        },
        body: formData
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const result = await response.json();
      
      if (result.success) {
        message.success('教师添加成功');
        form.resetFields();
        setAvatarUrl('');
        setFormValues({
          name: '',
          briefIntro: '',
          detailedIntro: '',
          avatar: '',
          phone: ''
        });
        setModalVisible(false);
        fetchTeachers(); // 刷新列表
      } else {
        message.error(result.message || '添加失败');
      }
    } catch (error) {
      message.error('添加教师失败');
      console.error('添加教师错误:', error);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '讲师名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      render: (text, record) => (
        <Space>
          <Avatar 
            src={record.avatar && record.avatar.startsWith('http') 
              ? record.avatar 
              : `http://localhost:3001${record.avatar}`} 
          />
          <Text>{text}</Text>
        </Space>
      )
    },
    {
      title: '讲师简介',
      dataIndex: 'briefIntro',
      key: 'briefIntro',
      width: 200,
      ellipsis: true
    },
    {
      title: '上传人',
      dataIndex: 'uploader',
      key: 'uploader',
      width: 150
    },
    {
      title: '添加时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (date) => new Date(date).toLocaleString('zh-CN')
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => {
        // 获取当前用户信息
        const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
        
        return (
          <Space size="middle">
            <ActionPermissionGuard action="edit" userId={currentUser.id}>
              <Button 
                type="text" 
                icon={<EditOutlined />} 
                className={styles.editBtn}
                onClick={() => handleEditClick(record)}
              />
            </ActionPermissionGuard>
            <ActionPermissionGuard action="delete" userId={currentUser.id}>
              <Button 
                type="text" 
                icon={<DeleteOutlined />} 
                className={styles.deleteBtn}
                onClick={() => confirmDelete(record)}
              />
            </ActionPermissionGuard>
          </Space>
        );
      }
    }
  ];

  const [editingTeacher, setEditingTeacher] = useState(null);
  const [editModalVisible, setEditModalVisible] = useState(false);

  // 获取教师详情
  const fetchTeacherDetail = async (id) => {
    try {
      setLoading(true);
      const token = localStorage.getItem('token');
      const response = await fetch(`http://localhost:3001/api/teachers/${id}`, {
        headers: {
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
        }
      });
      const result = await response.json();
      
      if (result.success) {
        setEditingTeacher(result.data);
        setAvatarUrl(result.data.avatar);
        form.setFieldsValue({
          name: result.data.name,
          briefIntro: result.data.briefIntro,
          detailedIntro: result.data.detailedIntro,
          phone: result.data.phone,
          avatar: result.data.avatar
        });
        setEditModalVisible(true);
      } else {
        message.error('获取教师信息失败');
      }
    } catch (error) {
      message.error('获取教师信息失败');
      console.error('获取教师信息错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 处理编辑按钮点击
  const handleEditClick = (record) => {
    fetchTeacherDetail(record._id);
  };

  // 更新教师信息
  const handleUpdateTeacher = async () => {
    try {
      const values = await form.validateFields();
      const formData = new FormData();
      
      formData.append('name', values.name);
      formData.append('briefIntro', values.briefIntro);
      formData.append('detailedIntro', values.detailedIntro);
      formData.append('phone', values.phone || '');
      
      // 如果有新上传的头像
      if (typeof values.avatar !== 'string' && values.avatar) {
        formData.append('avatar', values.avatar);
      }

      const token = localStorage.getItem('token');
      const response = await fetch(`http://localhost:3001/api/teachers/${editingTeacher._id}`, {
        method: 'PUT',
        headers: {
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
        },
        body: formData
      });

      const result = await response.json();
      
      if (result.success) {
        message.success('教师信息更新成功');
        setEditModalVisible(false);
        fetchTeachers(); // 刷新列表
      } else {
        message.error(result.message || '更新失败');
      }
    } catch (error) {
      message.error('更新教师信息失败');
      console.error('更新教师错误:', error);
    }
  };

  // 删除教师
  const handleDeleteTeacher = async (id) => {
    try {
      setLoading(true);
      const token = localStorage.getItem('token');
      const response = await fetch(`http://localhost:3001/api/teachers/${id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : ''
        }
      });
      
      const result = await response.json();
      
      if (result.success) {
        message.success('教师删除成功');
        fetchTeachers(); // 刷新列表
      } else {
        message.error(result.message || '删除失败');
      }
    } catch (error) {
      message.error('删除教师失败');
      console.error('删除教师错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 确认删除弹窗
  const confirmDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除讲师 ${record.name} 吗？此操作不可恢复！`,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => handleDeleteTeacher(record._id),
      icon: <ExclamationCircleOutlined />
    });
  };


  return (
    <div className={styles.teacherContainer}>
      {/* 筛选区域 */}
      <Card 
        title="讲师筛选" 
        bordered={false} 
        className={styles.filterCard}
        extra={
          <ActionPermissionGuard action="add" userId={JSON.parse(localStorage.getItem('currentUser') || '{}').id}>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              className={styles.addButton}
              onClick={() => setModalVisible(true)}
            >
              添加讲师
            </Button>
          </ActionPermissionGuard>
        }
      >
        <div className={styles.filterRow}>
          <div className={styles.filterItem}>
            <span className={styles.filterLabel}>添加时间</span>
            <RangePicker 
              style={{ width: 240 }}
              placeholder={['开始日期', '结束日期']}
              onChange={(dates) => setSearchParams({...searchParams, dateRange: dates})}
            />
          </div>
          
          <Search
            placeholder="请输入讲师名称"
            style={{ width: 280 }}
            value={searchParams.name}
            onChange={(e) => setSearchParams({...searchParams, name: e.target.value})}
            onSearch={handleFilter}
          />
          
          <Button 
            type="primary" 
            icon={<FilterOutlined />}
            className={styles.filterButton}
            onClick={handleFilter}
            loading={loading}
          >
            筛选
          </Button>
        </div>
      </Card>
      
      {/* 讲师列表 */}
      <Card 
        title="讲师列表" 
        bordered={false} 
        className={styles.listCard}
      >
        <Table
          columns={columns}
          dataSource={teachers}
          rowKey="_id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            showTotal: total => `共 ${total} 条`,
            onChange: (page, pageSize) => setPagination({...pagination, current: page, pageSize}),
          }}
          scroll={{ x: 800 }}
        />
      </Card>

      {/* 添加讲师模态框 */}
      <Modal
        title={
          <div className={styles.modalHeader}>
            <ArrowLeftOutlined 
              className={styles.backIcon} 
              onClick={() => setModalVisible(false)}
            />
            <span>讲师 / 添加讲师</span>
          </div>
        }
        visible={modalVisible}
        onCancel={() => {
          form.resetFields();
          setAvatarUrl('');
          setModalVisible(false);
        }}
        footer={null}
        width={600}
        closable={false}
        className={styles.addTeacherModal}
      >
        <div className={styles.modalBody}>
          <Text className={styles.formHint}>请填写讲师相关信息</Text>
          
          <Form
            form={form}
            layout="vertical"
            className={styles.teacherForm}
            onFinish={handleAddTeacher}
            onValuesChange={handleFormChange}
            initialValues={formValues}
          >
            <Form.Item
              label="讲师名称"
              name="name"
              rules={[{ required: true, message: '请输入讲师名称' }]}
            >
              <Input 
                placeholder="请输入讲师名称" 
                value={formValues.name}
                onChange={(e) => setFormValues({...formValues, name: e.target.value})}
              />
            </Form.Item>

            <Form.Item
              label="上传照片"
              name="avatar"
              rules={[{ required: true, message: '请上传讲师头像' }]}
            >
              <Upload
                name="avatar"
                listType="picture-card"
                showUploadList={false}
                beforeUpload={async (file) => {
                  const isImage = file.type.startsWith('image/');
                  if (!isImage) {
                    message.error('只能上传图片文件!');
                    return false;
                  }
                  const isLt500K = file.size / 1024 < 500;
                  if (!isLt500K) {
                    message.error('图片大小不能超过500KB!');
                    return false;
                  }
                                     try {
                     const url = await handleAvatarUpload(file);
                     console.log('设置表单头像字段:', url);
                     form.setFieldsValue({ avatar: url });
                     message.success('头像上传成功');
                   } catch (error) {
                     console.error('头像上传失败:', error);
                     message.error('头像上传失败');
                   }
                  return false; // 阻止自动上传
                }}
                className={styles.avatarUpload}
                accept="image/jpeg,image/png"
              >
                {avatarUrl ? (
                  <div style={{ textAlign: 'center' }}>
                    <Avatar 
                      src={avatarUrl.startsWith('http') ? avatarUrl : `http://localhost:3001${avatarUrl}`} 
                      size={100} 
                      className={styles.teacherAvatar}
                    />
                    <div style={{ marginTop: 8, fontSize: 12, color: '#666' }}>
                      点击重新上传
                    </div>
                  </div>
                ) : (
                  <div className={styles.uploadTrigger}>
                    {uploading ? <LoadingOutlined /> : <PlusOutlined />}
                    <div className={styles.uploadText}>上传照片</div>
                  </div>
                )}
              </Upload>
            </Form.Item>

            <Form.Item
              label="个人简介"
              name="briefIntro"
              rules={[{ required: true, message: '请输入个人简介' }]}
            >
              <TextArea 
                rows={3} 
                placeholder="请输入简短的个人简介" 
                maxLength={100}
                showCount
                value={formValues.briefIntro}
                onChange={(e) => setFormValues({...formValues, briefIntro: e.target.value})}
              />
            </Form.Item>

            <Form.Item
              label="手机号"
              name="phone"
            >
              <Input 
                placeholder="请输入手机号（可选）" 
                value={formValues.phone}
                onChange={(e) => setFormValues({...formValues, phone: e.target.value})}
              />
            </Form.Item>

            <Form.Item
              label="详细介绍"
              name="detailedIntro"
            >
              <TextArea 
                rows={5} 
                placeholder="请输入详细的介绍信息"
                value={formValues.detailedIntro}
                onChange={(e) => setFormValues({...formValues, detailedIntro: e.target.value})}
              />
            </Form.Item>

            <div className={styles.formFooter}>
              <Button 
                htmlType="submit"
                type="primary" 
                className={styles.addButton}
                loading={loading}
              >
                立即添加
              </Button>
              <Button 
                className={styles.cancelButton}
                onClick={() => {
                  form.resetFields();
                  setAvatarUrl('');
                  setFormValues({
                    name: '',
                    briefIntro: '',
                    detailedIntro: '',
                    avatar: '',
                    phone: ''
                  });
                  setModalVisible(false);
                }}
              >
                取消
              </Button>
            </div>
          </Form>
        </div>
      </Modal>

      {/* 编辑教师模态框 */}
      <Modal
        title={
          <div className={styles.modalHeader}>
            <ArrowLeftOutlined 
              className={styles.backIcon} 
              onClick={() => setEditModalVisible(false)}
            />
            <span>讲师 / 编辑讲师</span>
          </div>
        }
        visible={editModalVisible}
        onCancel={() => {
          form.resetFields();
          setAvatarUrl('');
          setEditModalVisible(false);
        }}
        footer={null}
        width={600}
        closable={false}
        className={styles.addTeacherModal}
      >
        <div className={styles.modalBody}>
          <Text className={styles.formHint}>请修改讲师相关信息</Text>
          
          <Form
            form={form}
            layout="vertical"
            className={styles.teacherForm}
            onFinish={handleUpdateTeacher}
            onValuesChange={handleFormChange}
          >
            {/* 表单字段与添加模态框相同 */}
            <Form.Item
              label="讲师名称"
              name="name"
              rules={[{ required: true, message: '请输入讲师名称' }]}
            >
              <Input placeholder="请输入讲师名称" />
            </Form.Item>

            <Form.Item
              label="上传照片"
              name="avatar"
              rules={[{ required: true, message: '请上传讲师头像' }]}
            >
              <Upload
                name="avatar"
                listType="picture-card"
                showUploadList={false}
                beforeUpload={async (file) => {
                  const isImage = file.type.startsWith('image/');
                  if (!isImage) {
                    message.error('只能上传图片文件!');
                    return false;
                  }
                  const isLt500K = file.size / 1024 < 500;
                  if (!isLt500K) {
                    message.error('图片大小不能超过500KB!');
                    return false;
                  }
                  try {
                    const url = await handleAvatarUpload(file);
                    form.setFieldsValue({ avatar: url });
                    message.success('头像上传成功');
                  } catch (error) {
                    message.error('头像上传失败');
                  }
                  return false;
                }}
                className={styles.avatarUpload}
                accept="image/jpeg,image/png"
              >
                {avatarUrl ? (
                  <div style={{ textAlign: 'center' }}>
                    <Avatar 
                      src={avatarUrl.startsWith('http') ? avatarUrl : `http://localhost:3001${avatarUrl}`} 
                      size={100} 
                      className={styles.teacherAvatar}
                    />
                    <div style={{ marginTop: 8, fontSize: 12, color: '#666' }}>
                      点击重新上传
                    </div>
                  </div>
                ) : (
                  <div className={styles.uploadTrigger}>
                    {uploading ? <LoadingOutlined /> : <PlusOutlined />}
                    <div className={styles.uploadText}>上传照片</div>
                  </div>
                )}
              </Upload>
            </Form.Item>

            <Form.Item
              label="个人简介"
              name="briefIntro"
              rules={[{ required: true, message: '请输入个人简介' }]}
            >
              <TextArea rows={3} placeholder="请输入简短的个人简介" maxLength={100} showCount />
            </Form.Item>

            <Form.Item
              label="手机号"
              name="phone"
            >
              <Input placeholder="请输入手机号（可选）" />
            </Form.Item>

            <Form.Item
              label="详细介绍"
              name="detailedIntro"
            >
              <TextArea rows={5} placeholder="请输入详细的介绍信息" />
            </Form.Item>

            <div className={styles.formFooter}>
              <Button 
                htmlType="submit"
                type="primary" 
                className={styles.addButton}
                loading={loading}
              >
                保存修改
              </Button>
              <Button 
                className={styles.cancelButton}
                onClick={() => {
                  form.resetFields();
                  setAvatarUrl('');
                  setEditModalVisible(false);
                }}
              >
                取消
              </Button>
            </div>
          </Form>
        </div>
      </Modal>
    </div>
  );
}